#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, \
    ValidationError, Length
from app.models import User, Manufacturer


class RegistUser(FlaskForm):
    """
    用户注册表单
    """
    username = StringField(
        label="用户名：",
        # 验证器
        validators=[
            DataRequired('用户名不能为空！')
        ],
        description="用户名",
        # 附加选项,会自动在前端判别
        render_kw={
            "type": "text",
            "placeholder": "请输入用户名！",
            "class": "validate-username",
            "size": 38,
        }
    )
    email = StringField(
        label="邮箱：",
        # 验证器
        validators=[
            DataRequired('邮箱不能为空！'),
            Email('邮箱格式不正确')  # 用Email方法验证邮箱格式
        ],
        description="邮箱",
        # 附加选项,会自动在前端判别
        render_kw={
            "type": "email",
            "placeholder": "请输入邮箱！",
            "size": 38,
        }
    )
    manufacturer = StringField(
        label="厂商名称：",
        # 验证器
        validators=[
            DataRequired('厂商名称不能为空！'),
        ],
        description="厂商名称",
        # 附加选项,会自动在前端判别
        render_kw={
            "class": "text",
            "placeholder": "请输入厂商名称",
        }
    )
    password = PasswordField(
        # 标签
        label="密码：",
        # 验证器
        validators=[
            DataRequired('密码不能为空！')
        ],
        description="密码",
        # 附加选项,会自动在前端判别
        render_kw={
            "placeholder": "请输入密码！",
            "size": 38,
        }
    )
    repassword = PasswordField(
        label="确认密码：",
        validators=[
            DataRequired('确认密码不能为空！'),
            EqualTo('password', message="两次密码输入不一致！")  # 判断两次输入的密码是否一致
        ],
        description="确认密码",
        # 附加选项,会自动在前端判别
        render_kw={
            "placeholder": "请输入确认密码!",
            "size": 38,
        }
    )
    submit = SubmitField(
        '注册',
        render_kw={
            "class": "btn btn-primary login",
        }
    )

    # 账号认证，自定义验证器，判断输入的值是否唯一
    def validate_username(self, filed):
        """
         检测用户名是否已经存在
         :param field: 字段名
        """
        username = filed.data
        account = User.query.filter_by(username=username).count()
        if account == 1:
            raise ValidationError("用户名已经存在")

    def validate_email(self, filed):
        """
         检测注册邮箱是否已经存在
         :param field: 字段名
        """
        emails = filed.data
        manufacturer_num = Manufacturer.query.filter_by(uuid=emails).count()
        if manufacturer_num == 0:
            raise ValidationError("邮箱不存在，请重新输入！")

    def validate_manufacturer(self, filed):
        manufacturer = filed.data
        manufacturer_num = Manufacturer.query.filter_by(
            manufacturer_name=manufacturer).count()
        if manufacturer_num == 0:
            raise ValidationError("厂商不存在，请输入正确厂商！")


class LoginForm(FlaskForm):
    """
    用户登录表单
    """
    username = StringField(
        validators=[
            DataRequired("用户名不能为空！"),
        ],
        description="用户名",
        render_kw={
            "type": "text",
            "placeholder": "请输入用户名！",
            "class": "validate-username",
            "size": 38,
            "maxlength": 99
        }
    )
    password = PasswordField(
        validators=[
            DataRequired("密码不能为空！"),
            Length(min=3, message="密码长度不少于6位")
        ],
        description="密码",
        render_kw={
            "type": "password",
            "placeholder": "请输入密码！",
            "class": "validate-password",
            "size": 38,
            "maxlength": 99
        }
    )
    verify_code = StringField(
        'VerifyCode',
        validators=[DataRequired()],
        render_kw={
            "class": "validate-code",
            "size": 18,
            "maxlength": 4,
        }
    )
    submit = SubmitField(
        '登录',
        render_kw={
            "class": "btn btn-primary login",
        }
    )

    # 验证账号，命名规则：validate_ + 字段名。如果要验证密码，则可以创建函数validate_pwd
    def validate_user(self, field):
        account = field.data
        admin = User.query.filter_by(username=account).count()
        if admin == 0:
            raise ValidationError("账号不存在! ")


class PasswordForm(FlaskForm):
    """
     修改密码表单
     """
    old_password = PasswordField(
        label="原始密码 ：",
        validators=[
            DataRequired("原始密码不能为空！")
        ],
        description="原始密码",
        render_kw={
            "placeholder": "请输入原始密码！",
            "size": 38,
        }
    )
    password = PasswordField(
        label="新密码 ：",
        validators=[
            DataRequired("新密码不能为空！")
        ],
        description="新密码",
        render_kw={
            "placeholder": "请输入新密码！",
            "size": 38,
        }
    )
    repassword = PasswordField(
        label="确认密码 ：",
        validators=[
            DataRequired("请输入确认密码！"),
            EqualTo('password', message="两次密码不一致！")
        ],
        description="确认密码",
        render_kw={
            "placeholder": "请输入确认密码！",
            "size": 38,
        }
    )
    submit = SubmitField(
        '确认修改',
        render_kw={
            "class": "btn btn-primary login",
        }
    )

    def validate_old_password(self, field):
        from flask import session
        old_password = field.data
        user_id = session["user_id"]
        user = User.query.get(int(user_id))
        if not user.check_password(old_password):
            raise ValidationError("原始密码错误！")
